package org.advanced.expand;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author John.zhang
 * @version Id: ForkJoins, v 1.0 2020/12/12 15:41 ZhiYong Exp $
 * 计算1-10的累加
 */
public class ForkJoins extends RecursiveTask<Integer> {

    private final int THRESHOLD = 2;

    private int start;

    private int end;

    public ForkJoins(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                System.out.println("start:" + start + "-end:" + end);
                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            ForkJoins left = new ForkJoins(start, middle);
            ForkJoins right = new ForkJoins(middle + 1, end);
            left.fork();
            right.fork();
            Integer leftResult = left.join();
            Integer rightResult = right.join();
            sum += leftResult + rightResult;
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoins forkJoins = new ForkJoins(1, 10);
        ForkJoinTask<Integer> result = forkJoinPool.submit(forkJoins);
        System.out.println(result.get());
    }
}
